const app = require('express')();
const cp = require('child_process');
const http = require('http').Server(app);
const io = require('socket.io')(http);

app.get('/', function(req, res){
	res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
	socket.on('chat', function(msg){
		io.emit('chat', msg);
	});
});

const port = 3000;
http.listen(port, function(){
	console.log('listening on *:3000');

    var ip = getIPAdress();
    console.log(ip);
    cp.exec('start chrome http://' + ip + ':' + port);
});


/*var server = app.listen(3000, () => {
	var ip = getIPAdress();
	var port = server.address().port;
	
    cp.exec('start http://' + ip + ':' + port);
    console.log('listening on port %d', port);
});*/


/**
 * 获取本机IP
 * @return {[string]} [IP地址]
 */
function getIPAdress() {
    var interfaces = require('os').networkInterfaces();
    for (var devName in interfaces) {
        var iface = interfaces[devName];
        for (var i = 0; i < iface.length; i++) {
            var alias = iface[i];
            if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
                return alias.address;
            }
        }
    }
}